<template>
    <div class="wrapper">
      <el-row :gutter="32" v-loading="loading">
        <el-col :span="12" style="position: relative" >
          <el-carousel class="carousel" ref="carousel" :height="height + 'px'" indicator-position="none"
                       :interval="interval" @change="carouselChange" :initial-index="now">
            <el-carousel-item class="item" v-for="(item, index) in list" :key="index">
              <!--suppress HtmlUnknownTarget -->
              <img :alt="item.name" :src="item.image2"/>
            </el-carousel-item>
          </el-carousel>
          <div class="indicator">
            <ul>
              <li v-for="(item, index) in list" :key="item.name" @click="changeImage(index)"
                  :class="{active: index === now}">
                <!--suppress HtmlUnknownTarget -->
                <img :src="item.image" :alt="item.name"/>
              </li>
            </ul>
          </div>
        </el-col>

        <el-col class="right" :span="12" style="text-align: left">
          <el-rate class="score" :value="score" disabled :max="5" :allow-half="true"/>
          <span class="name">{{name}}</span>
          <div>
            <span class="price" v-if="selectSubPrice">{{selectSubPrice}}</span>
            <template v-else>
              <span class="price">{{minPrice}}</span>
              <span class="price-s">-</span>
              <span class="price">{{maxPrice}}</span>
            </template>
          </div>
          <p class="description">{{description}}</p>
          <div class="radio-wrapper">
            <span style="width: 10%">分类</span>
            <div style="width: 90%; display: inline-block">
              <el-radio-group v-model="typeId" class="radio-group">
                <template v-for="item in types" >
                  <el-radio :label="item.value" :border="true" :key="item.value" style="margin: 8px">
                    {{item.name}}</el-radio>
                </template>
              </el-radio-group>
            </div>
          </div>
          <el-row class="number-wrapper" :gutter="32">
           <el-col :span="12">
             数量:<el-input-number class="quantity" size="small" :min="1" :max="selectSubCount"
                                       v-model="number"/>
           </el-col>
            <el-col :span="12">
              库存:<el-input-number class="available" size="small" :min="0"
                                         v-model="selectSubCount" :disabled="true"/>
            </el-col>
          </el-row>
          <div class="but-wrapper">
            <el-button class="btn" :loading="carLoading" type="" icon="el-icon-goods" @click="handleAddGoodCar"
                    :disabled="btnCarDisabled">加入购物车</el-button>
            <el-button class="btn" :loading="wishLoading" type="" icon="el-icon-star-off"
                       @click="handleEnshrineGood">收藏商品</el-button>
            <el-button class="btn" :loading="buyLoading" type="primary" @click="handleToSell"
                       :disabled="btnSellDisabled">立即购买</el-button>
          </div>
          <span class="span1">SKU: N/A</span>
          <span class="span2"> accessories, fashion, summer </span>
          <ul class="share">
            <li><a href="#">
              <i class="fa fa-facebook-f"/>
            </a></li>
            <li><a href="#">
              <i class="fa fa-twitter"/>
            </a></li>
            <li><a href="#">
              <i class="fa fa-instagram"/>
            </a></li>
            <li><a href="#">
              <i class="fa fa-pinterest"/>
            </a></li>
            <li><a href="#">
              <i class="fa fa-google-plus"/>
            </a></li>
          </ul>
        </el-col>
      </el-row>
    </div>
</template>

<script>
import { ResultCode } from '@/constants/constants'
import { addToCar } from '@/api/ApiUserCar'
import AddUserCarDTO from '@/api/entity/AddUserCarDTO'
import { addEnshrineGood } from '@/api/ApiEnshrineGoods'
import { mapActions } from 'vuex'

export default {
  name: 'GoodDetail',
  props: {
    data: {
      type: [Object],
      request: true
    },
    height: {
      type: Number,
      default: 800
    },
    interval: {
      type: Number,
      default: 6000
    }
  },
  data () {
    return {
      buyLoading: false,
      wishLoading: false,
      carLoading: false,
      name: '',
      score: 0,
      description: '',
      minPrice: 0,
      maxPrice: 0,
      number: '0',
      typeId: 0,
      types: [],
      now: 0,
      list: [],
      loading: false,

      subs: [],
      selectSubCount: 0
    }
  },
  computed: {
    id () {
      return this.data && this.data.id ? this.data.id : 0
    },
    selectSub () {
      if (this.subs && this.subs.length > 0 && this.typeId > 0) {
        for (let i = 0; i < this.subs.length; i++) {
          if (this.subs[i].id === this.typeId) {
            return this.subs[i]
          }
        }
      }
      return null
    },
    selectSubPrice () {
      if (this.selectSub) {
        return this.selectSub.price
      }
      return null
    },
    btnCarDisabled () {
      return !(this.typeId && this.typeId > 0)
    },
    btnSellDisabled () {
      return !(this.typeId && this.typeId > 0)
    }
  },
  methods: {
    ...mapActions('user', ['freshCarGoods', 'freshCollectionGoods']),
    initData () {
      this.score = 0
      this.number = 0
      this.typeId = 0
      this.types = []
      this.now = 0
      this.list = []

      this.subs = []
    },
    changeImage (index) {
      this.now = index
      this.$refs.carousel.setActiveItem(index)
    },
    carouselChange (index) {
      this.now = index
      this.$emit('change', this.list[index])
    },
    convertGoodDetail (vm, good) {
      if (!good || !good.id) {
        return
      }
      const temp = {}
      temp.name = good.name
      temp.score = good.score
      temp.description = good.description
      const subs = good['subGoodList']
      if (subs && typeof subs === 'object') {
        vm.subs = subs
        subs.forEach((item, index) => {
          if (index === 0) {
            temp.minPrice = item.price
            temp.maxPrice = item.price
          }
          if (temp.minPrice > item.price) {
            temp.minPrice = item.price
          }
          if (temp.maxPrice < item.price) {
            temp.maxPrice = item.price
          }
          vm.types.push({
            name: item['subGoodName'],
            value: item.id
          })
        })
      }
      Object.assign(vm, temp)

      const list = []
      const pictures = good['goodPictureList']
      if (pictures && typeof pictures === 'object') {
        pictures.forEach(item => {
          list.push({
            id: item.id,
            name: item.id + '',
            image: item.image,
            image2: item.image
          })
        })
      }
      vm.list = list
    },
    freshData () {
      this.initData()
      this.convertGoodDetail(this, this.data)
    },
    /**
     * 检验数据，正确返回true，否则返回false
     */
    checkData () {
      if (!(this.typeId && this.typeId > 0)) {
        this.$message.error('请先选择商品分类')
        return false
      }
      if (!(this.number && this.number > 0)) {
        this.$message.error('商品数量不能小于1')
        return false
      }
      return true
    },
    /**
     * 添加购物车
     */
    handleAddGoodCar () {
      if (!this.checkData()) {
        return
      }
      this.carLoading = true
      const params = AddUserCarDTO.instance()
      params.setCount(this.number)
      params.setGoodId(this.typeId)
      addToCar(params, data => {
        if (data && data.code === ResultCode.OK) {
          this.$message.success('添加购物车成功')
          // noinspection JSValidateTypes
          this.freshCarGoods(1, 40)
        }
      }, () => {
        this.carLoading = false
      })
    },
    /**
     * 收藏商品
     */
    handleEnshrineGood () {
      this.wishLoading = true
      addEnshrineGood(this.id, data => {
        if (data && data.code === ResultCode.OK) {
          this.$message.success('收藏商品成功')
          // noinspection JSValidateTypes
          this.freshCollectionGoods()
        }
      }, () => {
        this.wishLoading = false
      })
    },
    /**
     * 立即购买
     */
    handleToSell () {
      if (!this.checkData()) {
        return
      }
      this.$router.push('/toOrder/' + this.id + '/' + this.typeId + '/' + this.number)
    }
  },
  mounted () {
    this.freshData()
  },
  watch: {
    data () {
      this.freshData()
    },
    selectSub (val) {
      this.selectSubCount = val.count
    }
  }
}
</script>

<style lang="scss" scoped>

  .wrapper{

    .carousel{

      .item{

        img{
          width: 100%;
          height: 100%;
        }

      }

    }

    .indicator{
      height: 89px;
      margin: 0 10%;
      position: absolute;
      bottom: 10px;
      left: 0;
      width: 80%;
      z-index: 100;
      overflow-x: auto;
      overflow-y: hidden;

      ul{
        display: block;
        list-style: none;
        white-space: nowrap;
        overflow-x: visible;

        li{
          display: inline-block;
          width: 70px;
          height: 70px;
          margin:9px;
          border: 2px;
          cursor: pointer;

          img{
            width: 100%;
            height: 100%
          }

        }

        .active{
          border: 2px solid #959595;
        }

      }

    }

    .right{
      padding: 24px 0;

      .name{
        margin: 20px 0;
        display: block;
        color: #333333;
        text-decoration: none;
        outline: none;
        font-weight: 700;
        font-size: 30px;
        line-height: 1.4;
        font-family: 'Roboto Condensed', sans-serif;
        text-align: left;
      }

      .price{
        font-weight: 700;
        color: #ff7353;
        display: inline-block;
        text-decoration: none;
        font-size: 24px;
        line-height: 32px;
        font-family: 'Roboto Condensed', sans-serif;
        margin-bottom: 24px;
      }

      .price-s{
        color: #ff7353;
        font-family: 'Roboto Condensed', sans-serif;
        margin: 0 10px 16px;
        font-size: 24px;
        line-height: 32px;
      }

      .description{
        font-size: 16px;
        margin-bottom: 38px;
        line-height: 26px;
        font-weight: 400;
        color: #777777;
        font-family: 'Lato', sans-serif;
        height: 156px;
        min-height: 156px;
      }

      .radio-wrapper{
        margin-bottom: 30px;

        .radio-group{
          margin-left: 30px;
        }

      }

      .number-wrapper{
        margin-bottom: 30px;

        .quantity, .available{
          margin-left: 20px;
        }

      }

      .but-wrapper{

        .btn{
          margin-right: 20px;
        }

      }

      .span1{
        margin-top: 20px;
      }

      .span1, .span2{
        display: block;
        font-size: 12px;
        font-family: 'Lato', sans-serif;
        color: #999999;
        line-height: 26px;
      }

      .share{
        list-style: none;
        display: block;
        margin-top: 20px;

        li{
          display: inline-block;
          color: #999999;
          font-size: 16px;
          text-decoration: none;
          outline: none;
          background-color: transparent;
          margin-right:10px;

          i:hover{
            color: #333333;
          }

          i{
            color: #999999;
          }

        }

      }

    }

  }

</style>
